package main

//https://www.kancloud.cn/sliver_horn/gorm/1861159
import (
	"fmt"
	"github.com/jinzhu/gorm"
	"time"
)

//scope 用做持久化的对象来初始化
/**
注册一个新的回调
删除现有的回调
替换现有的回调
注册回调的顺序
*/
//Callbacks 降低代码的耦合性，重复性

type Model struct {
	ID         int `gorm:"primary_key" json:"id"`
	CreatedOn  int `json:"created_on"`
	ModifiedOn int `json:"modified_on"`
	DeletedOn  int `json:"deleted_on"`
}

func init() {
	db, err := gorm.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/test?charset=utf8&parseTime=True&loc=Local")
	// 如果设置禁用表名复数形式属性为 true，`User` 的表名将是 `user`
	db.SingularTable(true)
	if err != nil {
		panic(err)
	}
	err = db.DB().Ping()
	if err != nil {
		db.Close()
	}
	Db = db
}

func updateTimeStampForCreateCallback(scope *gorm.Scope) {
	if !scope.HasError() {
		nowTime := time.Now().Unix()
		if createTimeField, ok := scope.FieldByName("CreatedOn"); ok {
			if createTimeField.IsBlank {
				createTimeField.Set(nowTime)
			}
		}
		if modifyTimeField, ok := scope.FieldByName("ModifiedOn"); ok {
			if modifyTimeField.IsBlank {
				modifyTimeField.Set(nowTime)
			}
		}

	}
}
func updateTimeStampForUpdateCallback(scope *gorm.Scope) {
	if _, ok := scope.Get("gorm:update_column"); !ok {
		scope.SetColumn("ModifiedOn", time.Now().Unix())
	}
}

func deleteCallback(scope *gorm.Scope) {
	if !scope.HasError() {
		var extraOption string
		//scope.Get("gorm:delete_option") 检查是否手动指定了delete_option
		if str, ok := scope.Get("gorm:delete_option"); ok {
			extraOption = fmt.Sprint(str)
		}
		//获取我们约定的删除字段，若存在则 UPDATE 软删除，若不存在则 DELETE 硬删除
		deletedOnField, hasDeletedOnField := scope.FieldByName("DeletedOn")
		//Unscoped 删除
		if !scope.Search.Unscoped && hasDeletedOnField {
			scope.Raw(fmt.Sprintf(
				"UPDATE %v SET %v=%v%v%v",
				//返回引用的表名，这个方法 GORM 会根据自身逻辑对表名进行一些处理
				scope.QuotedTableName(),
				scope.Quote(deletedOnField.DBName),
				scope.AddToVars(time.Now().Unix()),
				//返回组合好的条件SQL，看一下方法原型很明了
				addExtraSpaceIfExist(scope.CombinedConditionSql()),
				addExtraSpaceIfExist(extraOption),
			)).Exec()
		} else {
			scope.Raw(fmt.Sprintf(
				"DELETE FROM %v%v%v",
				scope.QuotedTableName(),
				addExtraSpaceIfExist(scope.CombinedConditionSql()),
				addExtraSpaceIfExist(extraOption),
			)).Exec()

		}

	}

}

func addExtraSpaceIfExist(str string) string {
	if str != "" {
		return " " + str
	}
	return ""
}

func main() {
	//绑定到钩子上
	Db.Callback().Create().Replace("gorm:update_time_stamp", updateTimeStampForCreateCallback)
	Db.Callback().Delete().Replace("gorm:delete", deleteCallback)
}

//func updateCreated(scope *gorm.Scope){
//	if scope.HasColumn("Created") {
//		scope.SetColumn("Created",gorm.NowFunc())
//	}
//}
//func main() {
//	Db.Callback().Create().Register("update_created_at",updateCreated)
//	Db.Callback().Create().Remove("gorm:create")
//
//}
